package com.bilibili.liveremind.module.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bilibili.liveremind.module.common.WxCommon;
import com.bilibili.liveremind.module.entity.BaseUser;
import com.bilibili.liveremind.module.entity.UserLive;
import com.bilibili.liveremind.module.service.IBaseUserService;
import com.bilibili.liveremind.module.service.IUserLiveService;
import com.bilibili.liveremind.module.util.WxUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/live")
public class LiveInfoController {

    @Autowired
    private IBaseUserService baseUserService;
    @Autowired
    private IUserLiveService userLiveService;


    @GetMapping("/liveInfo")
    public Map<String, Object> liveInfo(String jsCode){
        //获取openid
        String wxOpenId = WxUtil.getWxOpenId(jsCode);
        //2.查询是否已有openid ? 获取直播列表 ：添加到数据库然后获取直播列表
        LambdaQueryWrapper<BaseUser> baseUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        baseUserLambdaQueryWrapper.eq(BaseUser::getWxOpenId,wxOpenId);
        BaseUser baseUser = baseUserService.getOne(baseUserLambdaQueryWrapper);
        if (null == baseUser){
            baseUser = new BaseUser();
            baseUser.setName("");
            baseUser.setWxOpenId(wxOpenId);
            baseUser.setCreateDate(new Date());
            baseUserService.save(baseUser);
        }
        //3.根据openid获取直播列表
        LambdaQueryWrapper<UserLive> userLiveLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLiveLambdaQueryWrapper.eq(UserLive::getUserId,baseUser.getId());
        userLiveLambdaQueryWrapper.eq(UserLive::getDeleteMark,0);
        userLiveLambdaQueryWrapper.orderByDesc(UserLive::getCreateDate);
        List<UserLive> userLiveList = userLiveService.list(userLiveLambdaQueryWrapper);

        Map<String,Object> resMap = new HashMap<>();
        resMap.put("userId",baseUser.getId());
        resMap.put("data",userLiveList);
        return resMap;
    }

}
